import request from "@/utils/request";

export async function getAudioList(params) {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      method: "audio.getList",
      params: {
        page: params.page || 1,
        page_size: params.page_size || 20,
      },
    });
    return response.data;
  } catch (error) {
    console.error("获取音频列表失败:", error);
    throw error;
  }
}

export async function playAudio(audioId, options = {}) {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      method: "audio.play",
      params: {
        audio_id: audioId,
        volume: options.volume || 80,
        repeat: options.repeat || 0,
        channel: options.channel || "all",
      },
    });
    return response.data;
  } catch (error) {
    console.error("播放音频失败:", error);
    throw error;
  }
}

/**
 * 停止音频播放
 * @param {string} playId 播放任务ID（可选，不提供则停止所有播放）
 * @returns {Promise<Object>} 停止结果
 */
export async function stopAudio(playId = null) {
  try {
    const params = {};
    if (playId) {
      params.play_id = playId;
    }

    const response = await request.post("/v1/jsonrpc2", {
      method: "audio.stop",
      params: params,
    });
    return response.data;
  } catch (error) {
    console.error("停止音频播放失败:", error);
    throw error;
  }
}

/**
 * 下载音频文件
 * @param {string} audioId 音频文件ID
 * @returns {Promise<Blob>} 返回音频文件的Blob对象
 */
export async function downloadAudio(audioId) {
  try {
    const chunks = [];
    let fileInfo = null;
    let currentChunk = 0;
    
    // 获取第一个分块和文件信息
    const firstChunkResponse = await request.post("/v1/jsonrpc2", {
      method: "audio.download",
      params: {
        audio_id: audioId,
        chunk_index: 0,
        chunk_size: 65536 // 64KB
      }
    });

    if (!firstChunkResponse.data?.result?.file_info) {
      throw new Error("无法获取文件信息");
    }

    fileInfo = firstChunkResponse.data.result.file_info;
    chunks.push(base64ToUint8Array(firstChunkResponse.data.result.chunk_data));

    // 下载剩余分块
    for (currentChunk = 1; currentChunk < fileInfo.total_chunks; currentChunk++) {
      const response = await request.post("/v1/jsonrpc2", {
        method: "audio.download",
        params: {
          audio_id: audioId,
          chunk_index: currentChunk,
          chunk_size: 65536
        }
      });

      if (!response.data?.result?.chunk_data) {
        throw new Error(`下载分块 ${currentChunk} 失败`);
      }

      chunks.push(base64ToUint8Array(response.data.result.chunk_data));
    }

    // 合并所有分块
    const completeFile = new Blob(chunks, { type: "audio/*" });

    // 验证文件大小
    if (completeFile.size !== fileInfo.size) {
      throw new Error("文件大小不匹配");
    }

    return completeFile;
  } catch (error) {
    console.error("下载音频失败:", error);
    throw error;
  }
}

/**
 * 将Base64字符串转换为Uint8Array
 * @param {string} base64 Base64编码的字符串
 * @returns {Uint8Array}
 */
function base64ToUint8Array(base64) {
  const binaryString = atob(base64);
  const length = binaryString.length;
  const bytes = new Uint8Array(length);
  
  for (let i = 0; i < length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  
  return bytes;
}

export async function deleteAudio(audioId) {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      method: "audio.delete",
      params: {
        audio_id: audioId,
      },
    });
    return response.data;
  } catch (error) {
    console.error("删除音频失败:", error);
    throw error;
  }
}

/**
 * 上传音频文件
 * @param {Object} params 上传参数
 * @param {number} params.chunkIndex 分块序号
 * @param {number} params.totalChunks 总分块数
 * @param {string} params.chunkData Base64编码的数据块
 * @param {Object} params.fileInfo 文件信息（仅第一块需要）
 * @param {string} params.fileInfo.name 文件名
 * @param {number} params.fileInfo.size 总大小（字节）
 * @param {string} params.fileInfo.type 音频类型
 * @param {string} params.fileInfo.md5 文件MD5校验值
 * @param {number} params.fileInfo.duration 音频时长（秒）
 * @param {string} params.fileInfo.description 音频描述（可选）
 * @returns {Promise<Object>} 上传结果
 */
export async function uploadAudio(params) {
  try {
    const requestData = {
      method: "audio.upload",
      params: {
        chunk_index: params.chunkIndex,
        total_chunks: params.totalChunks,
        chunk_data: params.chunkData,
      },
    };

    // 仅在上传第一个分块时附加文件信息
    if (params.chunkIndex === 0 && params.fileInfo) {
      requestData.params.file_info = {
        name: params.fileInfo.name,
        size: params.fileInfo.size,
        type: params.fileInfo.type,
        md5: params.fileInfo.md5,
      };

      // 添加可选参数
      if (params.fileInfo.duration) {
        requestData.params.file_info.duration = params.fileInfo.duration;
      }
      
      if (params.fileInfo.description) {
        requestData.params.file_info.description = params.fileInfo.description;
      }
    }

    const response = await request.post("/v1/jsonrpc2", requestData);
    return response.data;
  } catch (error) {
    console.error("上传音频失败:", error);
    throw error;
  }
}

/**
 * 获取音频输入设备列表
 * @returns {Promise<Object>} 设备列表
 */
export async function getAudioInputDevices() {
  try {
    const response = await request.post("/v1/jsonrpc2", {
      method: "audio.getInputDevices",
      params: {},
    });
    return response.data;
  } catch (error) {
    console.error("获取音频输入设备列表失败:", error);
    throw error;
  }
}
